package devicedbgui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import devicedbgui.data.Exe;
import devicedbgui.data.ExeDAO;
import devicedbgui.data.TestCase;
import devicedbgui.data.TestCaseDAO;
import devicedbgui.data.TestData;
import devicedbgui.data.TestDataDetail;
import devicedbgui.data.TestResult;
import devicedbgui.data.TestResultDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/** Displays results from running test case executable file */
public class TCResPanel extends javax.swing.JPanel {
    /* Stores test Case information */
    public ArrayList<TestData> listTestData = new ArrayList<TestData>();
    /* Stores name of executable file */
    private File exefile;
    /* Stores status of connection to database */
    private Connection conn = null;
    /* Stores device record */
    private String deviceRecord;
    /* Stores build id */
    private String buildId;
    /* Used to read ini file with test results */
    Properties p = new Properties();
    /* Test Case table format */
    DefaultTableModel model;
    /* Test Results table format */
    DefaultTableModel model2;
    GUI gui;
    boolean Notrun=false;
    /** Constructor creates all components belonging to panel */   
    public TCResPanel(File exefile, GUI gui) {
        initComponents();
        this.exefile = exefile;
        this.conn = gui.connection;
        this.gui=gui;
        String d;
        String res;
        model = (DefaultTableModel) table.getModel();
        model2 = (DefaultTableModel) table2.getModel();
        table.removeColumn(table.getColumnModel().getColumn(2));
        String fname=exefile.getName();
        fname=fname.substring(0, fname.lastIndexOf('.'));
        
        FileInputStream input = null;
        /* Reads available test cases from file */
        try {
        
        
        p.load(input=new FileInputStream(fname+".ini"));
        System.out.println("NAME: "+fname+".ini");
       
        if(!p.containsKey("tc")){Notrun=true;}
        else  {       
        readTestDataFromFile();
        
            int t = Integer.parseInt(p.getProperty("tc"));
            for (int i = 1; i < t + 1; i++) {

                d = "t" + i + "descr";
                res = "t" + i + "result";
                if (p.containsKey(d) && p.containsKey(res)) {
                    model.addRow(new Object[]{p.getProperty(d), p.getProperty(res), i});
                       
                }
            }
    }
         if (p.containsKey("err")){
            System.out.println("ERROR!!!!");
            if (gui.error==false)
            {  
                JOptionPane.showMessageDialog(new JFrame(), "Device not connected:\nCannot run some tests","Error 2", JOptionPane.ERROR_MESSAGE);
                gui.error=true;
            }
    
        }
       
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       if(model.getRowCount()==0){Notrun=true;}
       
        try {
            input.close();
                       } catch (IOException ex) {
            Logger.getLogger(TCResPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
}
/** Reads and parses test result from file */
    private void readTestDataFromFile() throws FileNotFoundException, IOException {
System.out.println("reading!!!!");
        TestData testData;
        TestDataDetail detail;
 
        int t = Integer.parseInt(p.getProperty("tc"));
        String d, res;
        for (int i = 1; i < t+1; i++) {
            d = "t" + i + "descr";
            res = "t" + i + "result";
            
            if (p.containsKey(d) && p.containsKey(res)) {
                testData = new TestData(exefile.getName(), p.getProperty(d), p.getProperty(res));

                // get test result of this testdata
                int c = Integer.parseInt(p.getProperty("t" + i + "dn"));
                for (int k = 1; k < c + 1; k++) {
                    if(!p.getProperty("t" + i + "d" + k + "descr").equals("~~")){
                    detail = new TestDataDetail(testData.FileName, p.getProperty("t" + i + "d" + k + "descr"),
                            p.getProperty("t" + i + "d" + k));
                    testData.addDetail(detail);
                }}

                // add to list
                listTestData.add(testData);
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table =  new javax.swing.JTable(){public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !table.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (table.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }};
        saveBtn = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        table2 = new javax.swing.JTable(){public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !table2.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (table2.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }};

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Test Cases", "Result", "Title 3"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.setGridColor(new java.awt.Color(204, 204, 255));
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(table);

        saveBtn.setText("Save");
        saveBtn.setMnemonic(KeyEvent.VK_S);
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        table2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Test Case", "Statement", "Result"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table2.setGridColor(new java.awt.Color(204, 204, 255));
        jScrollPane3.setViewportView(table2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(saveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(saveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)))
                .addGap(30, 30, 30))
        );
    }// </editor-fold>//GEN-END:initComponents
/** Saves test results to local computer */
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
    deviceRecord=gui.getDeviceRecord();
    buildId=gui.getBuildId();
    
    if (deviceRecord.equals("(select an item)") ||
            buildId.equals("(select an item)")) {
        JOptionPane.showMessageDialog(null, "Please choose a device and a build associated with this Test Case.",
                "Choose device and build", JOptionPane.INFORMATION_MESSAGE);
        return;
    }

    try {
        int id = Integer.parseInt(buildId);
        // save to table exe
        Exe exe = new Exe(-1, exefile.getName(), id);
        ExeDAO eDao = new ExeDAO(conn);
        eDao.insert(exe);
        int exeid = eDao.getLastID();

        // save to table TestCase
        TestCaseDAO tDao = new TestCaseDAO(conn);
        TestResultDAO trDao = new TestResultDAO(conn);
        TestCase testCase;
        TestResult testResult;
        for (TestData testData : listTestData) {
            // column description in table testcase have data in format: <TestCases>;<TestResult>
            testCase = new TestCase(-1, testData.TestCases + ";" + testData.TestResult, exeid);
            tDao.insert(testCase);
            id = eDao.getLastID();

            // save to table TestResult
            for (TestDataDetail detail : testData.listDetail) {
                testResult = new TestResult(-1, detail.Statement, detail.Result, new Date(), id);
                trDao.insert(testResult);
            }
        }

        // inform user
        JOptionPane.showMessageDialog(null, "Test data has been saved successfully.",
                "Save successfully to database", JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.toString(),
                "Error 1", JOptionPane.ERROR_MESSAGE);
        return;
    }
}//GEN-LAST:event_saveBtnActionPerformed
/* Determines which test case has been selected and shows associated test results */
private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
    System.out.print(table.getSelectedRow());
    int row = table.getSelectedRow();
    Object v = model.getValueAt(row, 2);
    Object s = model.getValueAt(row, 0);
    int c = Integer.parseInt(p.getProperty("t" + v.toString() + "dn"));
    int numrows = model2.getRowCount();

    for (int i = numrows - 1; i >= 0; i--) {
        model2.removeRow(i);
    }

    for (int i = 1; i < c + 1; i++) {
        if(p.getProperty("t" + v.toString() + "d" + i + "descr").equals("~~")){ continue;}
        model2.addRow(new Object[]{s, p.getProperty("t" + v.toString() + "d" + i + "descr"), p.getProperty("t" + v.toString() + "d" + i)});
        System.out.println("t" + v.toString() + "d" + i + "descr" + ", " + "t" + v.toString() + "d" + i);
    }

}//GEN-LAST:event_tableMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton saveBtn;
    private javax.swing.JTable table;
    private javax.swing.JTable table2;
    // End of variables declaration//GEN-END:variables
}
